<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="null"
    cancelText="关闭"
  >
    <a-row :gutter="10">
      <a-col :span="24">
        <a-card title="项目权限" :bodyStyle="bodyStyle">
          <user-project-permission-modal
            :tenantId="tenantId"
            :userId="userId"
            ref="userProjectPermissionModal"
            @selectProject="selectProject"
            @cleanData="cleanData"
          ></user-project-permission-modal>
        </a-card>
      </a-col>
      <!--<a-col :span="14">
        <a-card title="设备权限">
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery" >
              <a-row :gutter="24">
                <a-col :md="6" :sm="12">
                  <a-form-item label="设备ID">
                    <j-input placeholder="" v-model="queryParam.id"></j-input>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="12">
                  <a-form-item label="设备名称">
                    <j-input placeholder="" v-model="queryParam.name"></j-input>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="12">
                  <a-form-item label="设备序列号">
                    <j-input placeholder="" v-model="queryParam.devSerialNo"></j-input>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="12">
                  <a-button type="primary" icon="search" @click="searchQuery">搜索</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <span slot="action" slot-scope="text, record">
              <j-checkbox v-model="sport[record.id]" :options="record.funs" @change="onChange($event, record.id)"></j-checkbox>
            </span>

          </a-table>
        </a-card>
      </a-col>-->
    </a-row>
  </j-modal>
</template>

<script>
import { api, saveUserDevice, listUserDevice } from './service'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JCheckbox from '@comp/jeecg/JCheckbox'
import UserProjectPermissionModal from './UserProjectPermissionModal.vue'

export default {
  name: 'UserProjectModal',
  mixins: [JeecgListMixin],
  components: {
    JCheckbox,
    UserProjectPermissionModal
  },
  data() {
    return {
      title: '项目权限设置',
      width: 700,
      visible: false,
      bodyStyle: { 'min-height': '500px' },

      disableMixinCreated: true,
      tenantId: '',
      userId: '',
      projectId: '',

      // 表头
      columns: [
        {
          title: '设备ID',
          dataIndex: 'id'
        },
        {
          title: '设备名称',
          dataIndex: 'name'
        },
        {
          title: '设备序列号',
          dataIndex: 'devSerialNo'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      dataSource: [],

      sport: {},
      userDeviceMap: {},

      url: {
        list: ''
      }
    }
  },
  methods: {
    show(tenantId, userId) {
      this.tenantId = tenantId
      this.userId = userId
      this.visible = true
      this.dataSource = []
      this.url.list = ''
      this.queryParam = {}
      this.sport = {}
      this.userDeviceMap = {}
      this.$nextTick(() => {
        this.$refs.userProjectPermissionModal.cleanRadio()
        this.$refs.userProjectPermissionModal.returnUserProject()
      })
    },
    handleOk() {
      let that = this
      let param = []
      for (let deviceId in that.userDeviceMap) {
        let device = that.userDeviceMap[deviceId]
        if (that.sport[deviceId] !== undefined) {
          device.newAuths = that.sport[deviceId].trim(',').split(',')
          device.userId = that.userId
          device.tenantId = that.tenantId
          param.push(device)
        }
      }
      if (param.length === 0) {
        that.$message.warn('请选择设备功能')
      } else {
        saveUserDevice(that.userId, param).then(res => {
          if (res.success) {
            that.$message.success('保存成功')
            // that.close()
          } else {
            that.$message.error(res.message)
          }
        })
      }
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.visible = false
    },
    searchQuery() {
      if (!this.url.list) {
        this.$message.warning('请先选中项目！')
        return
      }
      this.loadData(1)
      this.getUserDevice()
    },
    selectProject(projectId) {
      this.url.list = api.listDevicesByProjId(projectId)
      this.projectId = projectId
      this.sport = {}
      this.userDeviceMap = {}
      this.searchQuery()
    },
    cleanData() {
      this.sport = {}
      this.userDeviceMap = {}
      this.dataSource = []
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      let that = this

      that.selectedRowKeys = selectedRowKeys
      that.selectionRows = selectionRows

      let userDeviceMap = {}
      for (let deviceId in that.userDeviceMap) {
        if (selectedRowKeys.indexOf(deviceId) !== -1) {
          userDeviceMap[deviceId] = that.userDeviceMap[deviceId]
        }
      }

      let selectionRowsMap = {}
      selectionRows.forEach(function(item) {
        selectionRowsMap[item.id] = item
      })

      selectedRowKeys.forEach(function(deviceId) {
        if (userDeviceMap[deviceId] === undefined) {
          userDeviceMap[deviceId] = {
            projectId: selectionRowsMap[deviceId].projectId,
            projectUuid: selectionRowsMap[deviceId].projectUuid,
            deviceId: selectionRowsMap[deviceId].id,
            deviceUuid: selectionRowsMap[deviceId].uuid
          }
        }
      })
      for (let deviceId in that.userDeviceMap) {
        let obj = userDeviceMap[deviceId]
        if (obj === undefined) {
          delete that.sport[deviceId]
        }
      }
      for (let deviceId in userDeviceMap) {
        let obj = that.userDeviceMap[deviceId]
        if (obj === undefined) {
          let funIdArr = []
          let funArr = selectionRowsMap[deviceId].funs
          funArr.forEach(item => {
            funIdArr.push(item.id)
          })
          that.sport[deviceId] = funIdArr.join(',')
        }
      }
      that.userDeviceMap = userDeviceMap
    },
    getUserDevice() {
      let that = this
      let params = { tenantId: that.tenantId, projectId: that.projectId }
      listUserDevice(that.userId, params).then(res => {
        if (res.success) {
          let keys = []
          that.userDeviceMap = {}
          res.result.forEach(function(item) {
            keys.push(item.deviceId + '')
            that.userDeviceMap[item.deviceId] = item

            let authJoin = item.newAuths.join(',')
            if (authJoin) {
              that.sport[item.deviceId] = authJoin
            }
          })
          that.selectedRowKeys = keys
        }
      })
    },
    reWriterWithSlot(arr) {
      for (let item of arr) {
        if (item.children && item.children.length > 0) {
          this.reWriterWithSlot(item.children)
          let temp = Object.assign({}, item)
          temp.children = {}
          this.projectTree.push(temp)
        } else {
          this.projectTree.push(item)
          item.scopedSlots = { title: 'title' }
        }
      }
    },
    onChange(values, deviceId) {
      let that = this
      that.sport[deviceId] = values
      that.sport = Object.assign({}, this.sport)
      that.dataSource.forEach(function(item) {
        if (item.id === deviceId) {
          that.deviceChange(item)
        }
      })
    },
    deviceChange(record) {
      let that = this
      let deviceId = record.id
      let values = that.sport[deviceId]
      let idx = this.selectedRowKeys.indexOf(deviceId)
      if (values) {
        if (idx === -1) {
          that.selectedRowKeys.push(deviceId)
          that.userDeviceMap[deviceId] = {
            projectId: record.projectId,
            projectUuid: record.projectUuid,
            deviceId: record.id,
            deviceUuid: record.uuid
          }
        }
      } else {
        if (idx !== -1) {
          that.selectedRowKeys.splice(idx, 1)
          delete that.userDeviceMap[deviceId]
        }
      }
    }
  }
}
</script>

<style scoped>
::v-deep .ant-tree li span.ant-tree-switcher {
  display: none;
}
</style>
